package com.wechatapp.mengyao.poetry.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.wechatapp.mengyao.poetry.interceptor.JwtInterceptor;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.TimeZone;

/**
 * @author yanghuaxu
 * @date 2025/5/21 8:57
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    private static final String[] jwtExcludePathPatterns = new String[]{
            "/api/v1/user/login",
            "/api/v1/user/token",
            "/api/v1/poetry/everyday",
            "/api/v1/poetry/type",
            "/api/v1/user/check_token_status",
            "/api/v1/tab_bar/item",
    };

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(jwtInterceptor())
                .addPathPatterns("/api/v1/**")
                .excludePathPatterns(jwtExcludePathPatterns);
    }

    @Bean
    public HandlerInterceptor jwtInterceptor() {
        return new JwtInterceptor();
    }

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper()
                .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true)
                .setTimeZone(TimeZone.getTimeZone("GMT+8"));
        SimpleModule customJavaTimeModule = new SimpleModule();
        customJavaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer());
        objectMapper.registerModule(customJavaTimeModule);
        return objectMapper;
    }

    @Bean
    public RestTemplate restTemplate() {
        // 使用HttpComponentsClientHttpRequestFactory代替默认工厂，以获得更好的性能和超时控制
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();

        // 设置连接超时（单位：毫秒）
        factory.setConnectTimeout(5000);
        // 设置读取超时（单位：毫秒）
        factory.setReadTimeout(15000);

        return new RestTemplate(factory);
    }

    public static class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
        private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        @Override
        public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider provider)
                throws IOException {
            gen.writeString(value.format(formatter));
        }
    }
}